﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TekaMUD.Engine.Blocks;
using TekaMUD.Engine.Framework;


namespace TekaMUD.Engine
{
	public class PlayerManager
	{
		private static Dictionary<string, Player> _playerDB;
		
		private static object SyncRoot = new object();
		
		public static Player GetNewPlayer()
		{
			Player p = new Player()
			{ 
				Status = PlayerStatus.New, 
				AutoLook = true				
			};

			p.Health.Hydration = 100;
			p.Health.Hydration_Max = 100;
			p.Health.HP_Max = 100;
			p.Health.HP_Cur = 100;
			p.Health.HP_Min = -1;

            EntityManager.RegisterInstance(p);

			return p;
		}

		static PlayerManager()
		{
			_playerDB = new Dictionary<string, Player>();
		}

		public static LoginResult Login(string login, string password)
		{
			Player p;

			lock (SyncRoot)
			{
				if (_playerDB.ContainsKey(login))
					p = _playerDB[login];
				else
					p = null;
			}

			if (p == null)
				return new LoginResult() { Result = LoginResultEnum.PlayerNotFound };

			if (!Crypto.CompareHashes(Crypto.GetMD5Hash(password), p.PasswordHash))
				return new LoginResult() { Result = LoginResultEnum.PasswordInvalid };

			return new LoginResult() { Result = LoginResultEnum.Accepted, Player = p };
		}

		public Player FindPlayerByLogin(string login)
		{
			lock (SyncRoot)
			{
				if (_playerDB.ContainsKey(login))
					return _playerDB[login];
				else
					return null;				
			}
		}

		public static void Register(Player player)
		{
			lock (SyncRoot)
			{
				player.Status = PlayerStatus.Active;
				_playerDB[player.Name] = player;

			}
		}

		public static void Remove(Player player)
		{
			Logger.LogDebug("Unregistering player " + player.Name);
			EntityManager.Unregister(player);
			
		}
	}

	public class LoginResult
	{
		public LoginResultEnum Result { get; set; }
		public Player Player { get; set; }
	}

	public enum LoginResultEnum
	{
		PlayerNotFound,
		PasswordInvalid,
		NotAllowed,
		Accepted
	}
}
